package com.money.demo.thread;

import com.money.activemq.MQProducer;
import com.money.dao.MoneyMapper;
import com.money.demo.common.MoneyBuilder;
import com.money.demo.object.MoneyBag;
import com.money.domain.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;



public class Producer implements Runnable{

    private Money money;


    public Producer(Money money) {
        this.money = money;
    }

    @Override
    public void run() {

        while (true){
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            MoneyBuilder builder=new MoneyBuilder(money.getTotal(), money.getCount());
            double all=0.0;
            List<MoneyBag> bags=new ArrayList<>();

            for(int i=0; i<money.getCount(); i++){
                MoneyBag bag=new MoneyBag();
                bag.setId(System.currentTimeMillis());
                bag.setSender(money.getSender());
                bag.setSenderName(money.getSenderName());
                bag.setGroup(money.getGroupId());
                bag.setGroupName(money.getGroupName());
                bag.setTotal(money.getTotal());
                bag.setCount(money.getCount());
                bag.setTime(money.getTime());

                double num=builder.getRandomMoney(money.getTotal() / (money.getCount() / 2));
                bag.setMoney(num);
                bags.add(bag);

                all+=num;

                System.out.println("用户"+money.getSender()+"生成的第"+(i+1)+"个红包，金额为："+num);
            }

            try {
                MQProducer.produce(money.getGroupId()+"", bags);
            } catch (JMSException e) {
                e.printStackTrace();
            }


//        while (!Constants.MONEY_BAGS.offer(vals)){
//            try {
//                Thread.currentThread().wait(5000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e.getCause());
//            }
//        }

            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);

            System.out.println("用户"+money.getSender()+"生成的红包总额为："+df.format(all));




        }



    }


    public Money getMoney() {
        return money;
    }

    public void setMoney(Money money) {
        this.money = money;
    }
}
